package com.yuexin.project.system.group.service;

import com.google.common.collect.Lists;
import com.yuexin.common.support.Convert;
import com.yuexin.common.utils.security.ShiroUtils;
import com.yuexin.project.system.group.domain.GroupUser;
import com.yuexin.project.system.group.domain.Groups;
import com.yuexin.project.system.group.domain.GroupsList;
import com.yuexin.project.system.group.formbean.GroupsListFormBean;
import com.yuexin.project.system.group.mapper.GroupUserMapper;
import com.yuexin.project.system.group.mapper.GroupsMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Arrays;
import java.util.Date;
import java.util.List;

/**
 * 人员组 服务层实现
 * 
 * @author zoncont.ahanu
 * @date 2019-04-30
 */
@Service
public class GroupsServiceImpl implements IGroupsService {
	@Autowired
	private GroupsMapper groupsMapper;

	@Autowired
	private GroupUserMapper groupUserMapper;

	/**
     * 查询人员组信息
     * 
     * @param id 人员组ID
     * @return 人员组信息
     */
    @Override
	public Groups selectGroupsById(Integer id) {
	    return groupsMapper.selectGroupsById(id);
	}
	
	/**
     * 查询人员组列表
     * 
     * @param form 查找条件
     * @return 人员组集合
     */
	@Override
	public List<GroupsList> selectGroupsList(GroupsListFormBean form) {
	    return groupsMapper.selectGroupsList(form);
	}
	
    /**
     * 新增人员组
     * 
     * @param groups 人员组信息
     * @return 结果
     */
	@Override
	@Transactional(rollbackFor = Exception.class)
	public int insertGroups(Groups groups) {
		int result = groupsMapper.insertGroups(groups);
		batchInsertGroupUser(groups);
	    return result;
	}

	/**
	 * 批量新增人员组与人员关联
	 * @param groups
	 */
	private void batchInsertGroupUser(Groups groups){
		List<GroupUser> groupUsers = Lists.newArrayList();
		Date time = new Date();
		String userName = ShiroUtils.getLoginName();
		groups.getGroupUserIds().stream().forEach(item -> {
			GroupUser gu = new GroupUser();
			gu.setCompanyId(groups.getCompanyId());
			gu.setGroupId(groups.getId());
			gu.setUserId(item);
			gu.setCreateTime(time);
			gu.setCreateBy(userName);
			groupUsers.add(gu);
		});
		groupUserMapper.batchInsert(groupUsers);
	}

	/**
     * 修改人员组
     * 
     * @param groups 人员组信息
     * @return 结果
     */
	@Transactional(rollbackFor = Exception.class)
	@Override
	public int updateGroups(Groups groups) {
		groupUserMapper.deleteGroupUserByGroupId(groups.getId());
		batchInsertGroupUser(groups);
	    return groupsMapper.updateGroups(groups);
	}

	/**
     * 删除人员组对象
     * 
     * @param ids 需要删除的数据ID
     * @return 结果
     */
	@Override
	public int deleteGroupsByIds(String ids) {
		return groupsMapper.deleteGroupsByIds(Convert.toStrArray(ids));
	}
	
}
